package com.heer.gymnasium.fragment;

import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.heer.api.ResponseData.ApiResponse;
import com.heer.api.callback.BaseCallback;
import com.heer.gymnasium.R;
import com.heer.gymnasium.activity.SiteDetailsActivity;
import com.heer.gymnasium.activity.SiteListActivity;
import com.heer.gymnasium.adapter.HomeSitesAdapter;
import com.heer.gymnasium.adapter.MyPagerAdapter;
import com.heer.gymnasium.constant.Type;
import com.heer.gymnasium.util.LoadImageUtil;
import com.heer.gymnasium.widget.MyListView;
import com.heer.model.AdMainBean;
import com.heer.model.SitesBean;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.circlenavigator.CircleNavigator;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager;
import retrofit2.Call;
import retrofit2.Response;

import static com.heer.gymnasium.constant.Constants.PAGESIZE;

/**
 * Created by rzw2 on 2017/4/5.
 */

public class MainHomeFragment extends BaseRefreshFragment {
    @BindView(R.id.viewpager_news)
    AutoScrollViewPager viewpagerNews;
    @BindView(R.id.tv_news)
    TextView tvNews;
    @BindView(R.id.indicator_news)
    MagicIndicator indicatorNews;
    @BindView(R.id.viewpager_sites)
    AutoScrollViewPager viewpagerSites;
    @BindView(R.id.tv_recommend)
    TextView tvRecommend;
    @BindView(R.id.btn_more)
    TextView btnMore;
    @BindView(R.id.list)
    MyListView list;
    @BindView(R.id.layout_refresh)
    SwipyRefreshLayout layoutRefresh;

    private MyPagerAdapter mNewsPagerAdapter;
    private MyPagerAdapter mSitesPagerAdapter;
    private HomeSitesAdapter mSitesAdapter;

    @Override
    protected int setConvertView() {
        return R.layout.fragment_main_home;
    }

    @Override
    protected void init() {
        super.init();
    }

    @Override
    protected void initView() {
        super.initView();
        tvNews.setVisibility(View.INVISIBLE);
        indicatorNews.setVisibility(View.INVISIBLE);
        tvRecommend.setVisibility(View.INVISIBLE);
        initRefreshList();
    }

    @Override
    protected void loadData(final boolean loadmore) {
        mAppHelper.apiService().getHotSiteList(null, Type.SITE_HOT, null, PAGESIZE, pageNo).enqueue(new BaseCallback<ApiResponse<SitesBean>>() {
            @Override
            public void onResponse(Call<ApiResponse<SitesBean>> call, Response<ApiResponse<SitesBean>> response) {
                layoutRefresh.setRefreshing(false);
                if (response.isSuccessful() && response.body().isSccessful()) {
                    if (loadmore)
                        mSitesAdapter.addItems(response.body().getData().getList());
                    else
                        mSitesAdapter.setItems(response.body().getData().getList());
                }
                if(response.body().isTokenExpire()){
                    toLogin();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<SitesBean>> call, Throwable t) {
                layoutRefresh.setRefreshing(false);
            }
        });

        mAppHelper.apiService().getMainAd("22").enqueue(new BaseCallback<ApiResponse<List<AdMainBean>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<AdMainBean>>> call, Response<ApiResponse<List<AdMainBean>>> response) {
                super.onResponse(call, response);
                if (response.isSuccessful() && response.body().isSccessful() && response.body().getData().size() > 0) {
                    initNewsViewpager(response.body().getData());
                    initNewsIndicator(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<AdMainBean>>> call, Throwable t) {
                super.onFailure(call, t);
            }
        });
        mAppHelper.apiService().getMainAd("23").enqueue(new BaseCallback<ApiResponse<List<AdMainBean>>>() {
            @Override
            public void onResponse(Call<ApiResponse<List<AdMainBean>>> call, Response<ApiResponse<List<AdMainBean>>> response) {
                super.onResponse(call, response);
                if (response.isSuccessful() && response.body().isSccessful() && response.body().getData().size() > 0) {
                    initSitesViewpager(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<List<AdMainBean>>> call, Throwable t) {
                super.onFailure(call, t);
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (null == viewpagerNews)
            return;
        if (hidden) {
            viewpagerNews.stopAutoScroll();
        } else {
            viewpagerNews.startAutoScroll();
        }
    }

    @OnClick(R.id.btn_more)
    public void onClick() {
        SiteListActivity.toSiteList(mContext);
    }

    private void initNewsViewpager(final List<AdMainBean> data) {

        List<View> imageViews = new ArrayList<>(); // 滑动的图片集合

        for (final AdMainBean item : data) {

            ImageView imageView = new ImageView(getActivity());
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            Glide.with(mContext).load(LoadImageUtil.getLoadImageUrl(item.getImages())).placeholder(R.mipmap.ic_launcher).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SiteDetailsActivity.startDetails(mContext, item.getSid());
                }
            });
            imageViews.add(imageView);

        }

        viewpagerNews.setAdapter(mNewsPagerAdapter = new MyPagerAdapter(imageViews));
        viewpagerNews.startAutoScroll();
        viewpagerNews.setBorderAnimation(false);
        viewpagerNews.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (tvNews != null)
                    tvNews.setText(data.get(position).getTitle());
            }
        });
    }

    private void initNewsIndicator(List<AdMainBean> data) {
        CircleNavigator circleNavigator = new CircleNavigator(mContext);
        circleNavigator.setCircleCount(data.size());
        circleNavigator.setCircleColor(Color.WHITE);
        circleNavigator.setCircleClickListener(new CircleNavigator.OnCircleClickListener() {
            @Override
            public void onClick(int index) {
                viewpagerNews.setCurrentItem(index);
            }
        });
        indicatorNews.setNavigator(circleNavigator);
        ViewPagerHelper.bind(indicatorNews, viewpagerNews);
    }

    private void initSitesViewpager(final List<AdMainBean> data) {

        List<View> imageViews = new ArrayList<>(); // 滑动的图片集合

        for (final AdMainBean item : data) {

            final ImageView imageView = new ImageView(getActivity());
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            Glide.with(mContext).load(LoadImageUtil.getLoadImageUrl(item.getImages())).placeholder(R.mipmap.ic_launcher).into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    SiteDetailsActivity.startDetails(mContext, item.getSid());
                }
            });
            imageViews.add(imageView);

        }
        viewpagerSites.startAutoScroll();
        viewpagerSites.setBorderAnimation(false);
        viewpagerSites.setAdapter(mSitesPagerAdapter = new MyPagerAdapter(imageViews));
        viewpagerSites.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (tvRecommend != null) {
                    tvRecommend.setText(data.get(position).getTitle());
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initRefreshList() {
        list.setAdapter(mSitesAdapter = new HomeSitesAdapter(mContext));
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SiteDetailsActivity.startDetails(mContext, mSitesAdapter.getItem(position).getId());
            }
        });
        layoutRefresh.setOnRefreshListener(this);
    }
}

